<template>
	<view>
		<!-- 标题 -->
		<view class="login-top">
			<!-- logo -->
			<view class="login-top-image">
				<image :src="getStaticFilePath('/login/logo.png')"></image>
			</view>
			<!-- 名字 -->
			<view class="login-top-title">
				飞砂走石
			</view>
			<!-- 平台 -->
			<!-- <view class="login-top-title-text">
				客户在线下单采购平台
			</view> -->
		</view>
		<!-- <view class="login-content">
			<view class="login-li">
				<text class="iconfont iconshouji3"></text>
				<input v-model="iphone" type="number" maxlength="11" value="" />
				
				
			</view>
			<view class="login-li">
				<text class="iconfont icona-yanzhengma1"></text>
				<input v-model="code" type="number" maxlength="6" value="" />
				<view @click="getCode">
					{{codetext}}
				</view>
			</view>
			<view class="login-li">
				<text class="iconfont iconduanxin1"></text>
				<input v-model="yqm" type="number" maxlength="6" value="" />
				<view style="color: #666666;">
					邀请码
				</view>
			</view>
		</view> -->

		<view class="login-button" v-if="isPhone=='0'">
			<!-- @click="submitLogin" -->
			<!-- <button class="login-content-btn" @click="submitykLogin" :class="btncolor" type="primary">游客登录</button> -->
			<!-- <button class="login-content-btn" @click="submitLogin" :class="btncolor" type="primary">登录</button> -->

			<button class="login-content-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
				:class="btncolor" type="primary">点击授权手机号</button>
		</view>
		<!-- <view class="login-button" style="text-align: center;margin-top:60rpx;">
			
			<button type="primary"
			plain @click="getUserProfile">微信授权</button>
			

		</view> -->
		<view class="login-button" style="text-align: center;margin-top:60rpx;">
			<!-- <u-button type="success" size="medium" @click="LoginDL">微信授权</u-button> -->
			<!-- jcMesgFun -->
			<button type="primary" plain @click="judgementMessageSwitch">查看进厂码</button>
			<!-- <u-button style="margin-right: 50rpx;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" type="success" shape="circle">
				微信授权
			</u-button> -->
			<!-- <view @click="Subscribe">预约抢购</view> -->
		</view>
		<u-popup v-model="showOpenSettingDialog" mode="center" width="520rpx" :mask-close-able="false" height="300rpx"
			border-radius="18">
			<div class="mock-dialog">
				<div class="mock-dialog-content">
					<div class="mock-dialog-title">提示!</div>
					<div class="mock-dialog-text">
						{{tipsContent}}
					</div>
				</div>
				<div class="mock-dialog-button">
					<!-- <div class="color-gray" @click="dontOpenSetting">{{buttonCancelText}}</div> -->
					<u-button type="success" class="color-blue" @click="openSetting">{{buttonConfirmText}}</u-button>
				</div>
			</div>
		</u-popup>

		<!-- <view class="" style="width: 100%;margin-top: 40rpx;margin-bottom: 40rpx;text-align: center;">
			<button style="background-color: #fff; border: none; width: 160rpx;padding: 0;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">
				<image @click="getUserInfo()" style="width: 80rpx;height: 80rpx;display: inline-block;"
					src="../../static/images/WX.png" mode="widthFix"></image>
					<view class="" style="text-align: center;">
						微信授权
					</view>
			</button>
				
				
				
		</view> -->

		<u-toast ref="uToast" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timeOut: 60,
				token: '',
				iphone: '',
				code: '',
				yqm: '',
				codetext: '获取验证码',
				ErpUserTypeText: '',
				cid: uni.getStorageSync('cid'),
				codewx: '',
				sessionKey: '',
				openid: '',
				oedrId: '',
				isPhone: 0, //0未绑定，1已绑定
				showOpenSettingDialog: false, // 授权询问弹框，uview
				tipsContent: '为了及时获取订单状态，请开启消息提醒！', // 弹框提示内容，
				buttonConfirmText: '去开启消息提醒',
				buttonCancelText: '不需要提醒',

			}
		},
		computed: {
			btncolor() {
				var i = ''
				var c = ''
				if (this.iphone && this.iphone != '') {
					i = this.iphone.trim()
				}
				if (this.code && this.code != '') {
					c = this.code.trim()
				}
				if (i.length == 11 && (c.length == 6 || c.length == 4)) {
					return ''
				} else {
					return 'login-content-btn-active'
				}
			}
		},
		onLoad(ops) {
			let that = this //保存当前作用域
			console.log(ops)
			that.oedrId = decodeURIComponent(ops.id)
			console.log(that.oedrId)
			if (that.oedrId) {
				this.getUserProfile()
			}

		},
		onShow() {},
		onLaunch: function() {
			//只有在基座运行的情况下才可以进行打印看到
			// const clientInfo = plus.push.getClientInfo()
			// console.log(clientInfo)
		},
		methods: {
			getUserProfile() {
				let code = "";
				let that = this //保存当前作用域

				uni.login({ //直接用这个调用微信接口
					onlyAuthorize: true,
					provider: 'weixin',
					success: function(response) { // 用微信登录的话就要去微信开发工具
						console.log(response) //这里打印就说明接口调用成功了，然后看message login ：ok
						//微信登录就完了，后面就是获取用户信息
						uni.request({
							url: that.baseUrl + '/system/getOpenId/',
							method: 'POST',
							dataType: 'json',
							data: {
								code: response.code,
							},
							success(response) {
								console.log(response)
								if (response.errMsg == 'request:ok') {
									// that.sessionKey = response.data.data.sessionKey
									that.openid = response.data.data.openid
									uni.setStorageSync('openid', that.openid)
									that.checkMobile()

								}

							}
						})

					}
				})
				// uni.getUserProfile({
				// 	// provider: "weixin",
				// 	lang: "zh_CN",
				// 	desc: '用于获取个人资料', // 这里的desc在微信开发文档中要求必须填写的
				// 	success: (res) => {
				// 		console.log("user", res);
				// 		that.userInfo = res.userInfo;
				// 		// let data = {
				// 		// 	channelId: this.channelId,
				// 		// 	token: code,
				// 		// 	signature: res.encryptedData,
				// 		// 	iv: res.iv,
				// 		// }


				// 	},
				// 	fail: err => {
				// 		console.log("获取用户信息失败");
				// 	}
				// })
			},


			// 判断消息订阅总开关是否打开
			judgementMessageSwitch(flag) {
				console.log(flag)
				let that = this
				uni.getSetting({
					withSubscriptions: true,
					success(res) {
						console.log(res)
						if (!res.subscriptionsSetting.mainSwitch) { // 订阅消息的总开关,如果是关着的，引导用户去打开
							// that.showOpenSettingDialog = true
							that.guideOpenSubscribeMessage()
						} else { // 如果开着，则继续向下打开弹窗，获取用户授权
							that.messageSubscription()
						}

					},
					fail() {
						that.messageSubscription() // 如果失败，则继续向下打开弹窗，获取用户授权
					}
				})
			},

			// 弹窗点订阅，开启消息订阅提醒
			// openSetting() {
			// 	// if (this.buttonConfirmText == '确定') {
			// 	// 	this.messageSubscription()
			// 	// 	return
			// 	// }


			// 	var that = this
			// 	uni.openSetting({
			// 		withSubscriptions: true,
			// 		complete(res) {
			// 			uni.getSetting({
			// 				withSubscriptions: true,
			// 				success(res) {
			// 					console.log(res)
			// 					if (res.subscriptionsSetting.mainSwitch) { // 订阅消息的总开关,如果是开着的
			// 						// that.tipsContent = '再次点击确定，弹出可订阅列表进行订阅'
			// 						// that.buttonCancelText = '取消'
			// 						// that.buttonConfirmText = '确定'
			// 						that.openSet()
			// 					} else {
			// 						that.showOpenSettingDialog = false;
			// 					}
			// 				}
			// 			})
			// 		}
			// 	})
			// },

			// 弹窗点不订阅
			// dontOpenSetting() {
			// 	this.showOpenSettingDialog = false;
			// },


			//引导用户，手动引导用户去设置页开启，
			guideOpenSubscribeMessage() {
				var that = this;
				uni.showModal({
					title: '提示',
					content: '检测到您没有开启订阅消息的权限，是否去设置？',
					success: function(sm) {
						if (sm.confirm) { // 用户点击了确定 可以调用删除方法了            
							that.openSet();
						} else if (sm.cancel) {
							uni.showToast({
								title: '您没有同意授权订阅消息，订阅失败',
								icon: 'none'
							});
						}
					}
				})
			},
			openSet() {
				var that = this
				uni.openSetting({
					withSubscriptions: true,
					success(res) {
						uni.getSetting({
							withSubscriptions: true,
							success(res) {
								console.log(res)

							}
						})
					}
				})
			},



			// 订阅申请弹出，只允许点击弹出
			messageSubscription() {
				// this.tipsContent = '为了及时获取订单状态，请开启消息提醒！' // 弹框提示内容，
				// this.buttonConfirmText = '去开启消息提醒'
				// this.buttonCancelText = '不需要提醒'
				let that = this
				console.log(that.isPhone)
				if (that.isPhone == 1) { //已绑定手机号
					// that.showOpenSettingDialog = false;
					let tmplId = ['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc',
						'gVutoHwiX2xXZ854-hEMvfCLcFH-VSijvBekmLuy_0Y',
						'fuDlCLRacLTaijUsl5LvPkb32koc_wbkuaVO60IoibQ'
					] // 模板ID，去小程序后台管理开一个，写进数组里，官方文档也有介绍
					uni.requestSubscribeMessage({
						tmplIds: tmplId,
						success(res) {
							console.log("success", res)
							// if (res['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'] == "reject"||res['gVutoHwiX2xXZ854-hEMvfCLcFH-VSijvBekmLuy_0Y'] == "reject"||res['fuDlCLRacLTaijUsl5LvPkb32koc_wbkuaVO60IoibQ']=='reject') {
							// 	console.log("拒绝")
							// 	that.guideOpenSubscribeMessage()
							// } 
							if (res['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'] == "accept" || res[
									'gVutoHwiX2xXZ854-hEMvfCLcFH-VSijvBekmLuy_0Y'] == "accept" || res[
									'fuDlCLRacLTaijUsl5LvPkb32koc_wbkuaVO60IoibQ'] == 'accept') {
								uni.showToast({
									title: '消息已订阅',
									icon: 'none'
								});
								uni.navigateTo({
									url: '/pages/driverqr/index?id=' + encodeURIComponent(that.oedrId)
								})
							}
						},
						fail() {

						}
					})
					
				}
				if (that.isPhone == 0) {
					console.log('请授权绑定手机号')
					uni.showToast({
						title: '请授权绑定手机号',
						icon: 'none'
					})
				}
			},
			bindOrder() {
				uni.request({
					url: this.baseUrl + '/wxUser/bindOrder',
					method: 'POST',
					dataType: 'json',
					data: {
						openId: uni.getStorageSync('openid'),
						orderId: this.oedrId
					},
					success: (res) => {
						console.log(res);
						uni.hideLoading();
						if (res.data.code == 200) {
							console.log(res)

						} else {
							uni.showToast({
								title: res.data.message,
								type: 'default',
								icon: false
							})
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '服务器连接超时',
							type: 'default',
							icon: false
						})
					}
				});
			},
			checkMobile() {
				uni.request({
					url: this.baseUrl + '/wxUser/checkMobile',
					method: 'POST',
					dataType: 'json',
					data: {
						openId: uni.getStorageSync('openid')
					},
					success: (res) => {
						console.log(res);
						uni.hideLoading();
						if (res.data.code == 200) {
							if (res.data.data == true) {
								this.isPhone = 1
								this.bindOrder()
							}

						} else {
							uni.showToast({
								title: res.data.message,
								type: 'default',
								icon: false
							})
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '服务器连接超时',
							type: 'default',
							icon: false
						})
					}
				});
			},

			jcMesgFun() {
				console.log(this.isPhone)
				if (this.isPhone == 1) { //已绑定手机号

					uni.getSetting({
						withSubscriptions: true,
						success(res) {
							console.log('1', res, '订阅信息', res.subscriptionsSetting);
							if (!res.subscriptionsSetting.mainSwitch) {
								uni.openSetting({ //打开设置页
									success(res) {
										console.log('打开设置页', res.authSetting);
									}
								})
							} else {
								uni.requestSubscribeMessage({
									tmplIds: ['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'],
									success(res) {
										console.log('requestSubscribeMessage 订阅信息', res);
										if (res['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'] ==
											"accept") { // 用户点击确定后
											console.log('用户订阅点击确定按钮');

											uni.navigateTo({
												url: '/pages/driverqr/index?id=' + this.oedrId
											})
											// that.getSubMsg()
										} else {
											console.log('拒绝');
											uni.showToast({
												title: '请允许订阅',
												type: 'none',
												icon: false
											})
										}
									},
									fail(errMessage) {
										console.log("订阅消息 失败 ", errMessage);
									}
								})
							}
						},
					})


					// uni.requestSubscribeMessage({
					// 	//此处填写刚才申请模板的模板ID
					// 	tmplIds: ['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'],
					// 	success(res) {
					// 		console.log(res)
					// 		if(res['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'] == "accept"){
					// 			console.log('用户订阅点击确定按钮');
					// 		}
					// 		else{
					// 			console.log('拒绝');
					// 			uni.showToast({
					// 				title: '请允许订阅',
					// 				type: 'none',
					// 				icon: false
					// 			})
					// 		}

					// 	},
					// 	fail:(res) => {
					// 		uni.showToast({
					// 			title: '订阅消息 失败',
					// 			type: 'none',
					// 			icon: false
					// 		})
					// 	}
					// })


				}
				if (this.isPhone == 0) {
					this.$refs.uToast.show({
						title: '请授权绑定手机号',
						type: 'default',
						icon: false
					})

					// uni.request({
					// 	url: this.baseUrl + '/wxUser/bind',
					// 	method: 'POST',
					// 	dataType: 'json',
					// 	data: {
					// 		code: this.codewx,
					// 		openId: this.openid
					// 	},
					// 	success: (res) => {
					// 		console.log(res);
					// 		uni.hideLoading();
					// 		if (res.data.code == 200) {
					// 			uni.requestSubscribeMessage({
					// 				//此处填写刚才申请模板的模板ID
					// 				tmplIds: ['is2ojtb-inlreRHMMJIPdbI23CbwGJFe93vkbgIfJhc'],
					// 				success(res) {
					// 					console.log(res)
					// 				}
					// 			})

					// 		} else {
					// 			this.$refs.uToast.show({
					// 				title: res.data.message,
					// 				type: 'default',
					// 				icon: false
					// 			})
					// 		}
					// 	},
					// 	fail: (res) => {
					// 		uni.hideLoading();
					// 		this.$refs.uToast.show({
					// 			title: '服务器连接超时',
					// 			type: 'default',
					// 			icon: false
					// 		})
					// 	}
					// });
				}

			},

			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					console.log('用户点击了接受');
					console.log(e);
					console.log(e);
					this.codewx = e.detail.code
					uni.request({
						url: this.baseUrl + '/wxUser/bind',
						method: 'POST',
						dataType: 'json',
						data: {
							code: this.codewx,
							openId: this.openid
						},
						success: (res) => {
							console.log(res);
							if (res.data.code == 200) {
								console.log(res)
								this.checkMobile()

							} else {
								uni.showToast({
									title: res.data.message,
									type: 'default',
									icon: false
								})
							}
						},
						fail: (res) => {
							uni.showToast({
								title: '服务器连接超时',
								type: 'default',
								icon: false
							})
						}
					});


					//e.detail这里会有三个属性
					//encryptedData
					//errMsg    
					//iv
				} else {
					this.$refs.uToast.show({
						title: '请授权绑定手机号',
						type: 'default',
						icon: false
					})
					console.log('用户点击了拒绝');
				}
			},
			async getUserInfo() {
				let that = this //保存当前作用域

				await uni.login({ //直接用这个调用微信接口
					onlyAuthorize: true,
					provider: 'weixin',
					success: function(response) { // 用微信登录的话就要去微信开发工具
						console.log(response) //这里打印就说明接口调用成功了，然后看message login ：ok
						//微信登录就完了，后面就是获取用户信息
						uni.request({
							url: that.baseUrl + '/system/getOpenId/',
							method: 'POST',
							dataType: 'json',
							data: {
								code: response.code,
							},
							success(response) {
								if (response.errMsg == 'request:ok') {
									that.sessionKey = response.data.data.sessionKey
								}

							}
						})

					}
				})
				// await uni.getUserProfile({
				// 	desc: '用于完善信息',
				// 	success: function(res) {
				// 		console.log("res", res)
				// 		uni.request({
				// 			url: that.baseUrl+'/system/getUserInfo',
				// 			method: 'POST',
				// 			dataType: 'json',
				// 			data: {
				// 				rawData: res.rawData,
				// 				signature: res.signature,
				// 				encryptedData: res.encryptedData,
				// 				iv: res.iv,
				// 				sessionKey: that.sessionKey
				// 			},
				// 			success(resc) {
				// 				console.log("登录成功", resc)
				// 			}
				// 		})
				// 	}
				// })

			}



			/**
			 *
			 * 获取用户信息
			 */
			// getUserInfo() {
			// 	// 展示加载框
			// 	uni.showLoading({
			// 		title: '加载中',
			// 	});
			// 	uni.getUserProfile({
			// 		desc: '登录后可同步数据',
			// 		success: async (obj) => {
			// 			console.log('obj', obj);
			// 			// 调用 action ，请求登录接口
			// 			// await this.login(obj);
			// 			uni.login({
			// 				provider: 'weixin',
			// 				success: (res) => {
			// 					console.log('res-login', res);
			// 					this.codewx = res.code;
			// 					console.log('code', res.code);
			// 					if (res.errMsg == 'login:ok') {
			// 						uni.request({
			// 								url: this.baseUrl + '/system/getOpenId/',
			// 								method: 'POST',
			// 								dataType: 'json',
			// 								data: {
			// 									code: this.codewx,
			// 								},
			// 							})
			// 							.then((res) => {
			// 								//获取到 openid 和 session_k后，自己的逻辑
			// 								console.log('授权登录', res[1].data);
			// 								console.log(res[1].data.data.openid);
			// 								// DoSomeThing.................
			// 							});
			// 					}
			// 				},
			// 			});
			// 		},
			// 		fail: () => {
			// 			uni.showToast({
			// 				title: '授权已取消',
			// 				icon: 'error',
			// 				mask: true,
			// 			});
			// 		},
			// 		complete: () => {
			// 			// 隐藏loading
			// 			uni.hideLoading();
			// 		},
			// 	});
			// },

		}
	}
</script>

<style scoped>
	.login-top {
		width: 45%;
		margin: 160rpx auto 40rpx auto;
	}

	.login-top-image {
		width: 200rpx;
		height: 200rpx;
		margin: 0rpx auto;
	}

	.login-top-image image {
		width: 200rpx;
		height: 200rpx;
	}

	.login-top-title {
		margin-top: 20rpx;
		font-size: 32px;
		font-family: Source Han Sans SC;
		font-weight: 500;
		color: #00A2F2;
		text-align: center;
	}

	.login-top-title-text {
		margin-top: 10rpx;
		font-size: 28rpx;
		font-family: Source Han Sans SC;
		color: #666666;
		text-align: center;
	}

	.login-content {
		padding: 60rpx 60rpx 0;
	}

	.login-li {
		display: flex;
		border-bottom: 1px solid #e3e3e3;
		margin-top: 20rpx;
		font-size: 26rpx;
		padding-left: 20rpx;
	}

	.login-li text {
		width: 40rpx;
		height: 60rpx;
		line-height: 60rpx;
	}

	.login-li input {
		flex: 1;
		height: 60rpx;
		line-height: 60rpx;
	}

	.login-li view {
		text-align: center;
		width: 260rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 24rpx;
		color: rgba(0, 168, 242, 1);
	}

	.login-li+.login-li {
		margin-top: 40rpx;
	}

	.login-li .iconfont {
		color: rgba(178, 178, 178, 1)
	}

	.login-content-btn {
		background-color: rgba(0, 122, 255, 1);
		color: #FFF;
	}

	.login-content-btn-active {
		background-color: rgba(0, 122, 255, .5);
	}

	.login-button {
		margin: 170rpx 40rpx 0;
	}

	.mock-dialog {
		padding: 20rpx;
	}

	.mock-dialog-title {
		color: red;
	}
</style>
